<template>
  <!-- 回访结果查询 -->
  <div class="visitTaskSearch">
    <ContentWrap>
      <FormContainer :column="4">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="100px">
          <el-form-item prop="objectMethod" label="客户生成方式">
            <el-select v-model="formData.objectMethod" placeholder="请选择客户生成方式" @change="objectMethodChange">
              <el-option label="导入数据" :value="0" />
              <el-option label="线上电商" :value="1" />
              <el-option label="线下门店" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item prop="groupId" label="所属业务组">
            <SearchSelectPicker
              url="/call-center/api/v1/businessGroup/page"
              placeholder="请选择所属业务组"
              lable-name="groupName"
              :value.sync="formData.groupId"
              :cur-options.sync="groupOption"
              multiple
              collapse-tags
              @selectChange="()=>{formData.customerService=''}"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="customerService" label="执行坐席">
            <!-- :params="{query:{groupId:formData.groupId},type:0}" -->
            <SearchSelectPicker
              url="/call-center/api/v1/staffInfo/page"
              :other-raw="{groupNos:groupOption.map(e=>e.groupNo)}"
              placeholder="请选择执行坐席"
              value-name="accountNo"
              lable-name="staffName"
              :parent-id="formData.groupId"
              :value.sync="formData.customerService"
              :lable.sync="accountName"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="taskType" label="任务类型">
            <SearchSelectPicker
              url="/call-center/api/v1/callBackTask/type/page"
              placeholder="请选择任务类型"
              lable-name="typeName"
              :value.sync="formData.taskType"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="taskId" label="任务名称">
            <SearchSelectPicker
              ref="taskIdSelect"
              url="/call-center/api/v1/callBackTask/taskManage"
              placeholder="任务名称"
              :params="{query:{objectMethod:formData.objectMethod},type:0}"
              lable-name="taskName"
              :parent-id="formData.objectMethod"
              :value.sync="formData.taskId"
              @selectChange="getQestionList"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="state" label="执行状态">
            <el-select v-model="formData.state" style="max-width:220px" clearable filterable>
              <el-option
                v-for="(option,index) in stateOptions"
                :key="index"
                :label="option.dictName"
                :value="option.dictCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="customerName" label="客户姓名">
            <el-input v-model="formData.customerName" placeholder="请输入客户姓名" clearable />
          </el-form-item>
          <el-form-item prop="customerPhone" label="联系电话">
            <el-input v-model="formData.customerPhone" placeholder="请输入联系电话" clearable />
          </el-form-item>
          <el-form-item v-if="formData.objectMethod===2" prop="officeCode" label="办事处">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/office/ref/page"
              method="get"
              placeholder="请选择办事处"
              lable-name="name"
              value-name="code"
              :value.sync="formData.officeCode"
              @selectChange="()=>{formData.disCode=''}"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item v-if="formData.objectMethod===2" prop="agent" label="经销商">
            <SearchSelectPicker
              ref="disSelect"
              :disabled="!formData.officeCode"
              url="/call-center/api/v1/mscInfo/dealer/ref/page"
              method="get"
              placeholder="请选择经销商"
              :params="{query:{officeCode:formData.officeCode},type:0}"
              lable-name="name"
              value-name="code"
              custom-name="codeOrName"
              :must-pid="true"
              :parent-id="formData.officeCode"
              :value.sync="formData.disCode"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item
            v-if="formData.objectMethod===1"
            prop="platformName"
            label="电商平台"
          >
            <!--  url="/call-center/api/v1/mscInfo/b2c/platform/page" -->
            <SearchSelectPicker
              url="/select-service/api/v1/eco/platform/page"
              :params="{query:null,type:0}"
              placeholder="请选择电商平台"
              value-name="code"
              lable-name="name"
              :value.sync="formData.platformCode"
              @selectChange="()=>{formData.shopCode=''}"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item
            v-if="formData.objectMethod===1"
            prop="shopName"
            label="电商店铺"
          >
            <!-- url="/call-center/api/v1/mscInfo/b2c/store/page" -->
            <SearchSelectPicker
              ref="storeSelect"
              url="/select-service/api/v1/eco/shop/page"
              placeholder="请选择电商店铺"
              :params="{query:{platformCode:formData.platformCode},type:0}"
              value-name="code"
              lable-name="name"
              :parent-id="formData.platformCode"
              :value.sync="formData.shopCode"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item v-if="formData.objectMethod===0" prop="remarks1" label="备注信息1">
            <el-input v-model="formData.remarks1" placeholder="请输入备注信息" clearable />
          </el-form-item>
          <el-form-item v-if="formData.objectMethod===0" prop="remarks2" label="备注信息2">
            <el-input v-model="formData.remarks2" placeholder="请输入备注信息" clearable />
          </el-form-item>
          <el-form-item v-if="formData.objectMethod===0" prop="remarks3" label="备注信息3">
            <el-input v-model="formData.remarks3" placeholder="请输入备注信息" clearable />
          </el-form-item>
          <el-form-item v-if="formData.objectMethod===0" prop="remarks4" label="备注信息4">
            <el-input v-model="formData.remarks4" placeholder="请输入备注信息" clearable />
          </el-form-item>
          <el-form-item v-if="formData.objectMethod===0" prop="remarks5" label="备注信息5">
            <el-input v-model="formData.remarks5" placeholder="请输入备注信息" clearable />
          </el-form-item>
          <el-form-item prop="date" :span="7" label="任务执行周期">
            <el-date-picker
              v-model="formData.date"
              type="daterange"
              opt
              value-format="yyyy-MM-dd"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item :span="5" label-width="79px">
            <Button @click="()=>{$refs.form.resetFields();accountName = $store.state.user.userCache.staffName}">重置</Button>
            <Button type="primary" :loading="loading" enter @click="queryHandle">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="button-container" style="padding-top:0">
        <ExportPane :table-config="tableConfig" :query-data-fun="queryHandle" :fields="exportFields" :other-raw="otherRaw" filename="回访结果">导出</ExportPane>
      </div>
      <table-box
        ref="table"
        :key="tableBoxKey"
        no-request
        :other-filters="otherFilters"
        :table-config="tableConfig"
        :selected-arry.sync="selectedAry"
        :other-raw="otherRaw"
        @selection-change="selectionChange"
      >
      </table-box>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import ExportPane from '@/components/ExportPane'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import { ccDict } from '@/api/dataDict'
import { filtersRaw, addOneDay, deepCopy } from '@/utils'
import { callBackTaskDetail } from '@/api/callBackTask'
import { questionnaireDetailById } from '@/api/questionnaire'
export default {
  name: 'ResultSearch',
  components: {
    ContentWrap,
    FormContainer,
    Button,
    ExportPane,
    SearchSelectPicker
  },
  data() {
    const validatorDate = (r, v, c) => {
      if (v && v.length > 0) {
        // 跨度不能超过两个月
        const start = new Date(v[0])
        const end = new Date(v[1])
        if (end.getTime() - start.getTime() > 61 * 24 * 60 * 60 * 1000) {
          c(new Error('跨度不能超过两个月'))
        } else {
          c()
        }
      } else {
        c(new Error('请选择任务执行周期'))
      }
    }
    return {
      tableBoxKey: 'tableBoxKey',
      groupOption: [],
      otherFilters: [], // 查询条件参数（处理后)
      selectedAry: [],
      accountName: '', // 当前登录账户名称
      formData: {
        objectMethod: 2,
        groupId: [],
        taskId: '',
        date: [],
        disCode: '',
        shopCode: '',
        customerService: ''
      },
      formRules: {
        objectMethod: {
          required: true,
          message: '请选择客户生成方式',
          trigger: 'change'
        },
        taskId: {
          required: true,
          message: '请选择任务名称',
          trigger: 'change'
        },
        date: {
          required: true,
          validator: validatorDate,
          trigger: 'change'
        }
      },
      stateOptions: [],
      otherRaw: {},
      loading: false,
      tableConfig: {
        interfacePath: '',
        sort: 'createTime',
        order: 'desc',
        pageFlag: true,
        hideFuncBar: true,
        // 表格字段动态配置
        setting: []
      },
      // 基础setting
      setting: [
        {
          prop: 'taskName',
          label: '任务名称',
          minWidth: 100
        },
        {
          prop: 'typeName',
          label: '任务类型',
          minWidth: 100
        },
        {
          prop: 'customerName',
          label: '客户姓名',
          minWidth: 100
        },
        {
          prop: 'customerPhone',
          label: '联系电话',
          minWidth: 100
        },
        {
          prop: 'state',
          label: '执行状态',
          minWidth: 120,
          formatData: v => this.getStateName(v)
          // propEnum: {
          //   domainCode: 'marketing',
          //   appCode: 'call-center',
          //   dictTypeCode: 'STATE'
          // }
        },
        {
          prop: 'customerServiceName',
          label: '执行坐席',
          minWidth: 120,
          formatData: v => {
            if (v.customerService) {
              return `${v.customerServiceName}(${v.customerService})`
            }
            return ''
          }
        },
        {
          prop: 'workOrderCode',
          label: '关联工单号',
          minWidth: 160,
          render: (h, row) => {
            return h('span', {
              class: 'btn-green work-order-code',
              on: {
                click: e => {
                  e.stopPropagation()
                  this.$router.push({ name: 'QueryOrderDetails', query: { workOrderNo: row.workOrderCode, form: 'any' }})
                }
              }
            }, row.workOrderCode)
          }
        },
        {
          prop: 'lastUpdateTime',
          label: '最后回访时间',
          minWidth: 140
        }
      ],
      // 导入数据
      exportSetting: [
        {
          prop: 'remarks1',
          label: '备注1'
        },
        {
          prop: 'remarks2',
          label: '备注2'
        },
        {
          prop: 'remarks3',
          label: '备注3'
        },
        {
          prop: 'remarks4',
          label: '备注4'
        },
        {
          prop: 'remarks5',
          label: '备注5'
        }
      ],
      // 非导入数据
      noExportSetting: [
        {
          prop: 'orderCode',
          minWidth: 160,
          label: '订单编号'
        }
      ],
      // 门店
      offlineSetting: [
        {
          prop: 'officeName',
          minWidth: 140,
          label: '办事处'
        },
        {
          prop: 'disName',
          minWidth: 140,
          label: '经销商'
        },
        {
          prop: 'shopName',
          minWidth: 140,
          label: '门店'
        }
      ],
      // 电商
      onlineSetting: [
        {
          prop: 'platformName',
          minWidth: 140,
          label: '平台'
        },
        {
          prop: 'shopName',
          minWidth: 140,
          label: '店铺'
        },
        {
          prop: 'buyer',
          minWidth: 140,
          label: '顾客ID'
        },
        {
          prop: 'officeName',
          minWidth: 140,
          label: '办事处'
        },
        {
          prop: 'serviceProviderName',
          minWidth: 140,
          label: '服务商名称'
        }
      ],
      questionSortData: {}
    }
  },
  computed: {
    exportFields() {
      return this.formData.objectMethod === 1 ? {
        // 顾客ID、办事处、服务商名称、客户地址这4个字段，
        // 客户地址造订单内是四级地址，请导出时拼接在客户地址1个字段内
        address: '客户地址'
        // '_customer_address_': {
        //   label: '客户地址',
        //   formatData: v => {
        //     return 'sssss'
        //   }
        // }
      } : {}
    }
  },
  watch: {

  },
  beforeMount() {
    this.accountName = this.$store.state.user.userCache.staffName
    this.formData.customerService = this.$store.state.user.userCache.accountNo
  },
  created() {
    if (this.$isShop()) {
      this.$set(this.formData, 'objectMethod', 1)
    }
  },
  mounted() {
    ccDict('STATE').then(res => {
      this.stateOptions = res.data
    })
    this.genSetting()
  },
  methods: {
    // 根据条件查询
    queryHandle(type) {
      return this.$refs.form.validate().then(() => {
        const list = []
        const otherRaw = {}
        // =
        const commonEq = ['customerService', 'taskType', 'taskId', 'state']
        const clientEq = ['platformCode', 'shopCode']
        const reEq = ['officeCode', 'disCode']
        // like
        const commonLike = ['customerName', 'customerPhone']
        const exportLike = ['remarks1', 'remarks2', 'remarks3', 'remarks4', 'remarks5']
        // in
        const commonIn = ['groupId']
        for (const [key, value] of Object.entries(this.formData)) {
          if (value === '' || value === null || value === undefined || key === 'objectMethod') {
            continue
          }
          if (value instanceof Array && value.length > 0) {
            if (key === 'date') {
              // if (this.formData.objectMethod === 1) {
              //   list.push(filtersRaw('startDate', value[0], '>='))
              //   list.push(filtersRaw('endDate', addOneDay(value[1]), '<='))
              // } else {
              otherRaw.startDate = value[0]
              otherRaw.endDate = addOneDay(value[1])
              // }
            }
            if (commonIn.includes(key)) {
              list.push(filtersRaw(key, value.join(','), 'in'))
            }
          } else {
          // 公共有参数groupId、customerService、taskType、taskId、state、customerName、customerPhone
            if (commonEq.includes(key)) {
              list.push(filtersRaw(key, value, '='))
            }
            if (commonLike.includes(key)) {
              list.push(filtersRaw(key, value, 'like'))
            }
            // 导入数据
            if (this.formData.objectMethod === 0) {
              if (exportLike.includes(key)) {
                list.push(filtersRaw(key, value, 'like'))
              }
            }
            // 电商数据
            if (this.formData.objectMethod === 1) {
              if (clientEq.includes(key)) {
                list.push(filtersRaw(key, value, '='))
              }
            }
            // 零售数据
            if (this.formData.objectMethod === 2) {
              if (reEq.includes(key)) {
                list.push(filtersRaw(key, value, '='))
              }
            }
          }
        }

        this.otherFilters = list
        this.otherRaw = otherRaw
        if (this.formData.objectMethod === 0) {
          // 数据导入任务查询
          this.tableConfig.interfacePath =
              '/call-center/api/v1/callBackTask/importResult/page'
        } else if (this.formData.objectMethod === 2) {
          // 线下任务查询
          this.tableConfig.interfacePath =
                '/call-center/api/v1/callBackTask/offlineResult/page'
        } else {
          // 线上任务查询
          this.tableConfig.interfacePath =
                '/call-center/api/v1/callBackTask/onlineResult/page'
        }
        // }
        if (type !== 'export') {
          this.refresh()
        }
        return list
      })
    },
    refresh(onPage) {
      this.$nextTick(() => {
        this.$refs.table.initTableData(onPage)
      })
    },
    // 获取状态名称
    getStateName(v) {
      if (!v.state) {
        return ''
      }
      for (const item of this.stateOptions) {
        if (v.state === item.dictCode || v.state.toString() === item.dictCode) {
          return item.dictName
        }
      }
    },
    // 客户生成方式选择
    changeCsTp(val) {},
    // 导出数据
    exportFunc() {
      // console.log('导出数据')
    },
    // 根据任务id查询任务问卷
    getQestionList(v) {
      callBackTaskDetail(v.id).then(res => {
        const qid = res.data.questionnaireId
        questionnaireDetailById(qid).then(res => {
          this.genSetting(res.data.questionnaireChapterDTOList)
          this.collectOption(res.data.questionnaireChapterDTOList)
        })
      })
    },
    collectOption(data) {
      const questionData = {}
      for (const d of data) {
        const qs = d.questionnaireQuestionDTOList
        if (qs && qs instanceof Array) {
          for (const q of qs) {
            const o = q.questionOptionDTOList
            if (o && o instanceof Array) {
              questionData[q.id] = o.map(e => e.id)
            }
          }
        }
      }
      this.questionSortData = questionData
    },
    selectionChange(val) {
      this.selectedAry = val
    },
    // 获取问题答案
    getAnswer(list, id) {
      if (list.length) {
        let ary = []
        list.forEach(i => {
          if (i.questionId === id) {
            const sortOption = (this.questionSortData || {})[i.questionId]
            ary = (deepCopy(i.optionDTOList) || []).sort((a, b) => {
              if (!sortOption || sortOption.length === 0) {
                return 0
              }
              const ai = sortOption.findIndex(v => v === a.optionId)
              const bi = sortOption.findIndex(v => v === b.optionId)
              if (ai < 0 || bi < 0) {
                return 0
              }
              return ai - bi
            }).map(e => {
              if (e.optionContent && e.inputContent) {
                return (e.optionContent + '(' + e.inputContent + ')')
              }
              if (!e.optionContent && e.inputContent) {
                return e.inputContent
              }
              if (e.optionContent && !e.inputContent) {
                return e.optionContent
              }
            })
          }
        })
        return ary.join(';')
      } else {
        return ''
      }
    },
    // 客户生成方式改变，刷新任务名称列表，重置任务名称id
    objectMethodChange(v) {
      this.formData.taskId = ''
      this.$set(this.formData, 'date', [])
      this.$refs.form.clearValidate()
      this.tableBoxKey = Math.floor(Math.random() * 0xffffff).toString(16)
      this.genSetting()
    },
    // 生成setting
    genSetting(questionnaireChapterDTOList = []) {
      // 导入数据
      const setting = deepCopy(this.setting)
      const questionList = []
      for (const chapter of questionnaireChapterDTOList) {
        for (const question of chapter.questionnaireQuestionDTOList) {
          questionList.push({
            label: question.questionTitle,
            minWidth: 200,
            formatData: v => {
              return this.getAnswer(v.callBackTaskResultDTOList, question.id)
            }
          })
        }
      }
      if (this.formData.objectMethod === 0) {
        this.$set(this.tableConfig, 'setting', setting.concat(deepCopy(this.exportSetting), questionList))
      } else if (this.formData.objectMethod === 2) {
        this.$set(this.tableConfig, 'setting', setting.concat(deepCopy(this.noExportSetting), deepCopy(this.offlineSetting), questionList))
      } else {
        this.$set(this.tableConfig, 'setting', setting.concat(deepCopy(this.noExportSetting), deepCopy(this.onlineSetting), questionList))
      }
    }
  }
}
</script>
<style lang='scss' module>
</style>
<style lang="scss">
.work-order-code{
  cursor: pointer;
  color: #16bc83;
}
</style>
